package com.cskaoyan.servlet;

import com.cskaoyan.bean.MarketRole;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.service.AdminRoleService;
import com.cskaoyan.service.AdminRoleServiceImpl;
import com.cskaoyan.util.MyBatisUtil;
import com.cskaoyan.util.ResponseUtil;
import com.cskaoyan.util.URIUtil;
import lombok.SneakyThrows;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author：LiuFan
 * @Project：Java50th_first
 * @Package：com.cskaoyan.servlet
 * @Date：2023/5/31 10:31
 */
@WebServlet("/admin/role/*")
public class AdminRoleServlet extends HttpServlet {
    private SqlSessionFactory sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
    private AdminRoleService roleService = new AdminRoleServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = URIUtil.getOperation(this.getClass(), req);
        switch (operation){
            case "/options" :
                options(req,resp);
                break;
        }
    }

    @SneakyThrows
    private void options(HttpServletRequest req, HttpServletResponse resp) {
        /*String name = StringUtil.isEmpty(req.getParameter("name")) ? null : req.getParameter("name");
        Integer page = StringUtil.isNotEmpty(req.getParameter("page"))?Integer.parseInt(req.getParameter("page")):null;
        Integer limit = StringUtil.isNotEmpty(req.getParameter("limit"))?Integer.parseInt(req.getParameter("limit")):null;
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");*/
        List<MarketRole> roleList = roleService.options();
        //Map key-value
        List<Map<String, Object>> options = new ArrayList<>(roleList.size());
        for (MarketRole role : roleList) {
            Map<String, Object> option = new HashMap<>(2);
            option.put("value", role.getId());
            option.put("label", role.getName());
            options.add(option);
        }
        ResponseUtil.responseOkJsonVo(resp, CommonData.data(options));
    }
}
